import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.function.Predicate;

/**
 * Created by zhourh on 2018/8/13.
 *
 * 给定两个数组，编写一个函数来计算它们的交集。

 示例 1:

 输入: nums1 = [1,2,2,1], nums2 = [2,2]
 输出: [2]
 示例 2:

 输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
 输出: [9,4]
 *
 */
public class IntersectionOfTwoArrays {

    public static void main(String[] args) {
        printArray(new IntersectionOfTwoArrays().intersection(new int[]{1,2,2,1}, new int[]{2,2}));
    }

    public int[] intersection(int[] nums1, int[] nums2) {
        if (nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0) {
            return new int[0];
        }

        Set<Integer> numSet1 = new HashSet<>();
        Set<Integer> numSet2 = new HashSet<>();
        for (int num : nums1) {
            numSet1.add(num);
        }

        for (int num : nums2) {
            numSet2.add(num);
        }

        numSet1.removeIf(new Predicate<Integer>() {
            @Override
            public boolean test(Integer num) {
                return !numSet2.contains(num);
            }
        });

        int[] ans = new int[numSet1.size()];

        Iterator<Integer> iterator = numSet1.iterator();
        int count = 0;
        while (iterator.hasNext()) {
            ans[count++] = iterator.next();
        }

        return ans;
    }


    private static void printArray(int[] array) {
        if (array == null) {
            System.out.println("null");
        }

        System.out.print("[");

        for (int i = 0; i < array.length; i++) {
            System.out.print( i == 0 ? array[i] : "," + array[i]);
        }

        System.out.print("]");
    }
}
